package com.atguigu.daijia.map.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.map.service.MapService;
import com.atguigu.daijia.model.form.map.CalculateDrivingLineForm;
import com.atguigu.daijia.model.vo.map.DrivingLineVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
@RequiredArgsConstructor
public class MapServiceImpl implements MapService {

    //远程调用
    private final RestTemplate restTemplate;

    @Value("${tencent.map.key}")
    private String key; //腾讯地图服务

    @Override
    public DrivingLineVo calculateDrivingLine(CalculateDrivingLineForm calculateDrivingLineForm) {
        //接口文档
        String url = "https://apis.map.qq.com/ws/direction/v1/driving/?from={from}&to={to}&key={key}";

        HashMap<String, String> map = new HashMap<>();
        //出发地的经纬度
        map.put("from", calculateDrivingLineForm.getStartPointLatitude() + "," + calculateDrivingLineForm.getStartPointLongitude());
        //目的地的经纬度
        map.put("to", calculateDrivingLineForm.getEndPointLatitude() + "," + calculateDrivingLineForm.getEndPointLongitude());
        //腾讯地图服务的key
        map.put("key", key);
        log.info("key:{}",key);
        //发送请求，得到结果
        JSONObject result = restTemplate.getForObject(url, JSONObject.class, map);
        //判断是否请求成功，status：0成功
        if (result.getIntValue("status") != 0){
            throw new GuiguException(ResultCodeEnum.MAP_FAIL);
        }

        //返回第一条最佳线路
        JSONObject route = result.getJSONObject("result").getJSONArray("routes").getJSONObject(0); //routes是数组形式的json
        DrivingLineVo drivingLineVo = new DrivingLineVo();

        //todo BigDecimal类可以完成高精度计算
        drivingLineVo.setDistance(route.getBigDecimal("distance") //获取结果返回的距离
                .divide(new BigDecimal(1000)) //数学运算，除以1000，因为默认返回的距离是米
                .setScale(2, RoundingMode.HALF_UP)); //保留两位小数，向上取整

        //预估时间
        drivingLineVo.setDuration(route.getBigDecimal("duration"));

        //返回路线的坐标点串polyline，它为数组
        drivingLineVo.setPolyline(route.getJSONArray("polyline"));
        return drivingLineVo;
    }
}
